package com.app.common;

import cn.hutool.core.date.DateUtil;
import com.app.model.SignIn;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SignInContinuous {

    /**
     * 连续登录天数
     *
     * @param signInList 登录列表
     * @return int
     * @throws ParseException 解析异常
     */
    public static int getContinuousSignInDay(List<SignIn> signInList) throws ParseException {
        int continuousDay = 1;
        boolean todaySignIn = false;
        String today = DateUtil.today();
        DateFormat dft = new SimpleDateFormat("yyy-MM-dd");
        for (int i = 0; i < signInList.size(); i++) {
            Date now = dft.parse(today);
            Date createTime = dft.parse(signInList.get(i).getCreateTime().toString());
            int intervalDay = distanceDay(now, createTime);
            //当天签到
            if (intervalDay == 0 && i == 0) {
                todaySignIn = true;
            } else if (intervalDay == continuousDay) {
                continuousDay++;
            } else {
                //不连续，终止判断
                break;
            }
        }
        if (!todaySignIn) {
            continuousDay--;
        }
        return continuousDay;
    }

    /**
     * 判断当天日期 与以往签到日期相隔天数
     *
     * @param largeDay 大日子
     * @param smallDay 小日子
     * @return int
     */
    private static int distanceDay(Date largeDay, Date smallDay) {
        long diffInMillis = largeDay.getTime() - smallDay.getTime();
        long diffInDays = diffInMillis / 24 / 60 / 60 / 1000;
        return (int) diffInDays;
    }
}
